#include "mywidget.h"
#include <QHBoxLayout>
#include <QApplication>
#include <QDesktopWidget>
#include <QQmlEngine>
#include <QQmlContext>
#include <QMenu>

constexpr int GLOBAL_OPEN_MOUSE_ENABLE{ 0 };
constexpr int GLOBAL_BACKGROUND_OPACITY{ 1 };
constexpr int GLOBAL_SYSTEM_MENU{ 0 };

MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
    m_view = new QQuickWidget(this);
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->addWidget(m_view);

    layout->setContentsMargins(0, 0, 0, 0);
    setLayout(layout);

    m_view->engine()->rootContext()->setContextProperty("widget",this);

    m_view->setSource(QUrl(QStringLiteral("qrc:/main.qml")));

    if(GLOBAL_BACKGROUND_OPACITY == 0)
    {
        this->setWindowFlags(this->windowFlags() | Qt::SubWindow | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);//窗口置顶，无边框
        setAttribute(Qt::WA_TranslucentBackground);
        setAutoFillBackground(true);//填充背景

        QPalette palette;
        palette.setBrush(QPalette::Window, QBrush(QColor(Qt::transparent)));
        this->setPalette(palette);

        m_view->setClearColor(QColor(Qt::transparent));    //qml 透明
    }

    this->setFixedSize(800, 1000);

    if(GLOBAL_OPEN_MOUSE_ENABLE != 0)
    {
        /*鼠标穿透*/
        SetWindowLong((HWND)winId(), GWL_EXSTYLE, GetWindowLong((HWND)winId(), GWL_EXSTYLE) |
                           WS_EX_TRANSPARENT | WS_EX_LAYERED);
    }

    if(GLOBAL_SYSTEM_MENU != 0)
    {
        setSystemMenu();
    }

//    m_thread = new QueryKeyThread(this);
//    connect(m_thread, &QueryKeyThread::queryResult, this, &MyWidget::queryResult);
//    connect(m_thread, &QueryKeyThread::mousePointChanged, this, &MyWidget::mousePointChanged);
//    m_thread->start();
}

void MyWidget::setSystemMenu()
{
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/image/image/logo.ico"));

    QMenu *menu = new QMenu(this);

    QAction *action = menu->addAction("退出");
    connect(action, &QAction::triggered, this, &MyWidget::systemExit);

    trayIcon->setContextMenu(menu);
    trayIcon->show();
}

void MyWidget::queryResult(QString name)
{
    (void)name;
    emit notifyMsg(gMouseX, gMouseY);
}


void MyWidget::mousePointChanged(int x, int y)
{
    emit notifyMousePos(x, y);
}

void MyWidget::systemExit(bool b)
{
    (void)b;
    qApp->quit();
}
